from django.shortcuts import render, redirect
import uuid
# Create your views here.
from rest_framework.permissions import IsAuthenticated
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from app01.utils.loggings import logger
from rest_framework.response import Response
from app01.libs.ipay import alipay, GATEWAY
from rest_framework.mixins import CreateModelMixin
from rest_framework.viewsets import GenericViewSet, ViewSet
from .models import Order
from .serializer import OrderSerializer
from app01.utils.response import APIResponse


class OrderView(GenericViewSet, CreateModelMixin):
    queryset = Order.objects.all()
    serializer_class = OrderSerializer
    authentication_classes = [JSONWebTokenAuthentication, ]
    permission_classes = [IsAuthenticated, ]

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data, context={'request': request})
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        pay_url = serializer.context.get('pay_url')

        return APIResponse(pay_url=pay_url)


class PaySuccessView(ViewSet):
    authentication_classes = []
    permission_classes = []

    # 给前端做二次校验用
    def list(self, resquest):
        out_trade_no = resquest.query_params.get('out_trade_no')
        order = Order.objects.filter(out_trade_no=out_trade_no, order_status=1).first()
        if order:
            return APIResponse()
        else:
            return APIResponse(code=101, msg='暂时还没收到你的付款')

    # 给支付宝用的--->必须把项目部署在公网上才能回调成功
    def create(self, request):
        try:
            # post提交的数据（支付宝回调格式：urlencoded，QueryDic）
            #
            # from django.http.request import QueryDict
            #
            # print(type(request.data))
            # 把QueryDic对象转成真正的dict对象，就可以修改，pop
            result_data = request.data.dict()
            # 我们的订单号
            out_trade_no = result_data.get('out_trade_no')
            # 支付宝的签名
            signature = result_data.pop('sign')
            from app01.libs.ipay import alipay
            result = alipay.verify(result_data, signature)
            if result and result_data["trade_status"] in ("TRADE_SUCCESS", "TRADE_FINISHED"):
                # 完成订单修改：订单状态、流水号、支付时间
                Order.objects.filter(out_trade_no=out_trade_no).update(order_status=1)
                # 完成日志记录
                logger.warning('%s订单支付成功' % out_trade_no)
                # 支付宝要的格式就这个格式
                return Response('success')
            else:
                logger.error('%s订单支付失败' % out_trade_no)
        except:
            pass
        return Response('failed')
